<template>
  <div class="work-order-detail">
    <el-page-header @back="goBack" :title="'返回'" :content="'送水工单 #' + workOrder.id" />
    
    <el-card class="detail-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>送水工单</span>
          <el-tag :type="getStatusType(workOrder.status)">{{ workOrder.status }}</el-tag>
        </div>
      </template>
      
      <el-descriptions :column="2" border>
        <el-descriptions-item label="工单编号">{{ workOrder.id }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ workOrder.application_time }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ workOrder.product_name }}</el-descriptions-item>
        <el-descriptions-item label="数量">{{ workOrder.quantity }}</el-descriptions-item>
        <el-descriptions-item label="单价">{{ workOrder.unit_price }} 元</el-descriptions-item>
        <el-descriptions-item label="总金额">{{ workOrder.total_amount }} 元</el-descriptions-item>
        <el-descriptions-item label="期望送达时间">{{ workOrder.expected_delivery_time }}</el-descriptions-item>
        <el-descriptions-item label="配送地址">{{ workOrder.delivery_address }}</el-descriptions-item>
        <el-descriptions-item label="联系人">{{ workOrder.contact_name }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ workOrder.contact_phone }}</el-descriptions-item>
        <el-descriptions-item label="优先级">
          <el-tag :type="getPriorityType(workOrder.priority)">{{ workOrder.priority }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      
      <div class="action-section" v-if="showActionButtons">
        <el-button 
          type="primary" 
          :disabled="!canAccept" 
          @click="handleAccept">接单</el-button>
        <el-button 
          type="warning" 
          :disabled="!canStartDelivery" 
          @click="handleStartDelivery">开始配送</el-button>
        <el-button 
          type="success" 
          :disabled="!canComplete" 
          @click="showCompleteDialog = true">完成配送</el-button>
      </div>
    </el-card>
    
    <!-- 完成工单对话框 -->
    <el-dialog
      title="完成送水工单"
      v-model="showCompleteDialog"
      width="500px">
      <el-form :model="completeForm" label-width="100px">
        <el-form-item label="配送结果">
          <el-input 
            type="textarea" 
            v-model="completeForm.result" 
            rows="4"
            placeholder="请输入配送结果描述" />
        </el-form-item>
        <el-form-item label="签收照片">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            list-type="picture-card">
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCompleteDialog = false">取消</el-button>
          <el-button type="primary" @click="handleComplete">确认送达</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { waterService } from '@/api/tasks'

export default {
  name: 'WaterOrderDetail',
  components: {
    Plus
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const loading = ref(true)
    const workOrder = ref({})
    const showCompleteDialog = ref(false)
    const completeForm = ref({
      result: '',
      images: []
    })
    
    // 根据工单状态判断是否显示操作按钮
    const showActionButtons = computed(() => {
      return ['待受理', '已确认备货中', '配送中'].includes(workOrder.value.status)
    })
    
    // 判断是否可以接单
    const canAccept = computed(() => {
      return workOrder.value.status === '待受理'
    })
    
    // 判断是否可以开始配送
    const canStartDelivery = computed(() => {
      return workOrder.value.status === '已确认备货中'
    })
    
    // 判断是否可以完成工单
    const canComplete = computed(() => {
      return workOrder.value.status === '配送中'
    })
    
    // 获取工单详情
    const fetchWorkOrderDetail = async () => {
      loading.value = true
      try {
        // 从路由参数中获取工单ID
        const id = route.params.id
        
        if (!id) {
          ElMessage.error('工单ID参数缺失')
          router.push('/staff/water-tasks')
          return
        }
        
        // 调用API获取工单详情
        const response = await waterService.getDetail(id)
        
        if (response.data && response.data.code === 200) {
          workOrder.value = response.data.data
        } else {
          ElMessage.error('获取工单详情失败')
        }
        
        loading.value = false
      } catch (error) {
        console.error('获取工单详情失败', error)
        ElMessage.error('获取工单详情失败')
        loading.value = false
      }
    }
    
    // 返回上一页
    const goBack = () => {
      router.back()
    }
    
    // 获取状态标签类型
    const getStatusType = (status) => {
      const statusMap = {
        '待受理': 'info',
        '已确认备货中': 'warning',
        '配送中': 'warning',
        '已送达': 'success',
        '已评价': 'success',
        '已取消': 'danger'
      }
      return statusMap[status] || ''
    }
    
    // 获取优先级标签类型
    const getPriorityType = (priority) => {
      const priorityMap = {
        '高': 'danger',
        '中': 'warning',
        '低': 'info'
      }
      return priorityMap[priority] || ''
    }
    
    // 处理接单
    const handleAccept = async () => {
      try {
        // 调用API接单
        const response = await waterService.updateStatus(workOrder.value.id, '已确认备货中')
        
        if (response.data && response.data.code === 200) {
          workOrder.value.status = '已确认备货中'
          ElMessage.success('接单成功')
        } else {
          ElMessage.error(response.data?.message || '接单失败')
        }
      } catch (error) {
        console.error('接单失败', error)
        ElMessage.error('接单失败')
      }
    }
    
    // 处理开始配送
    const handleStartDelivery = async () => {
      try {
        // 调用API开始配送
        const response = await waterService.updateStatus(workOrder.value.id, '配送中')
        
        if (response.data && response.data.code === 200) {
          workOrder.value.status = '配送中'
          ElMessage.success('已开始配送')
        } else {
          ElMessage.error(response.data?.message || '开始配送失败')
        }
      } catch (error) {
        console.error('开始配送失败', error)
        ElMessage.error('开始配送失败')
      }
    }
    
    // 处理文件上传
    const handleFileChange = (file) => {
      completeForm.value.images.push(file.raw)
    }
    
    // 处理完成工单
    const handleComplete = async () => {
      if (!completeForm.value.result.trim()) {
        ElMessage.warning('请输入配送结果描述')
        return
      }
      
      try {
        // 调用API完成工单
        const response = await waterService.updateStatus(workOrder.value.id, '已送达')
        
        if (response.data && response.data.code === 200) {
          // 添加处理记录
          try {
            await waterService.addRecord(
              workOrder.value.id,
              completeForm.value.result,
              completeForm.value.images
            )
          } catch (recordError) {
            console.error('添加配送记录失败', recordError)
          }
          
          workOrder.value.status = '已送达'
          showCompleteDialog.value = false
          ElMessage.success('送水工单已完成')
        } else {
          ElMessage.error(response.data?.message || '完成配送失败')
        }
      } catch (error) {
        console.error('完成配送失败', error)
        ElMessage.error('完成配送失败')
      }
    }
    
    onMounted(() => {
      fetchWorkOrderDetail()
    })
    
    return {
      loading,
      workOrder,
      showActionButtons,
      canAccept,
      canStartDelivery,
      canComplete,
      showCompleteDialog,
      completeForm,
      goBack,
      getStatusType,
      getPriorityType,
      handleAccept,
      handleStartDelivery,
      handleFileChange,
      handleComplete
    }
  }
}
</script>

<style scoped>
.work-order-detail {
  padding: 20px;
}

.detail-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-section {
  margin-top: 20px;
}

.section-title {
  font-weight: bold;
  margin-bottom: 10px;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}

.detail-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.detail-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
}

.action-section {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style> 